/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.web;

import javax.servlet.ServletContext;

import net.sourceforge.wurfl.core.DefaultWURFLHolder;
import net.sourceforge.wurfl.core.WURFLHolder;
import net.sourceforge.wurfl.core.WURFLManager;
import net.sourceforge.wurfl.core.WURFLUtils;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Spring context {@link WURFLHolder} decorator.
 * 
 * <p>
 * Build a new WURFLHolder from Spring ApplicationContext in ServletContext.
 * </p>
 * 
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: SpringWebWURFLHolder.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class SpringWebWURFLHolder implements WURFLHolder {

	/** Delegate WURFLHolder */
	private WURFLHolder delegate;

	/**
	 * Constructor by ServletContext
	 * 
	 * @param servletContext
	 *            The ServletContext contains application context definition.
	 */
	public SpringWebWURFLHolder(ServletContext servletContext) {

		ApplicationContext appContext = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);

		WURFLManager wurflManager = null;
		WURFLUtils wurflUtils = null;

		// FIXME By name or by type?
		String beansName[] = appContext.getBeanNamesForType(WURFLManager.class);
		if (beansName.length <= 0) {
			throw new IllegalStateException("A bean of type "
					+ WURFLManager.class.getName()
					+ " must be defined in application context.");

		}

		wurflManager = (WURFLManager) appContext.getBean(beansName[0]);

		// FIXME By name or by type?
		if (appContext.getBeanNamesForType(WURFLUtils.class).length > 0) {

			wurflUtils = (WURFLUtils) appContext.getBeansOfType(
					WURFLUtils.class).values().iterator().next();
		}

		this.delegate = new DefaultWURFLHolder(wurflManager, wurflUtils);
	}

	public WURFLManager getWURFLManager() {

		return delegate.getWURFLManager();
	}

	public WURFLUtils getWURFLUtils() {

		return delegate.getWURFLUtils();
	}

}
